<template>
  <div>
    <van-nav-bar title="登录" left-arrow @click-left="$router.push('/mine')" />
    <h1>优点达咨询</h1>
    <van-form @submit="onSubmit">
      <van-cell-group>
        <van-field
          v-model="username"
          name="用户名"
          label="用户名"
          left-icon="manager"
          placeholder="请输入手机号"
          :rules="rules.username"
          autocomplete
        />
        <van-field
          v-model="password"
          clearable
          name="密码"
          label="密码"
          type="password"
          left-icon="lock"
          placeholder="密码"
          :rules="rules.password"
          autocomplete
        />
      </van-cell-group>
      <van-button
        round
        type="info"
        size="large"
        native-type="submit"
        :disabled="isLoading"
        :loading="isLoading"
        loading-text="登录中"
      >
        提交
      </van-button>
    </van-form>
    <span @click="reg">没有账号，立即注册</span>
  </div>
</template>

<script>
import { userLogin } from '@/api/register'
import { mapMutations } from 'vuex'
export default {
  data() {
    return {
      isLoading: false,
      username: '',
      password: '',
      rules: {
        username: [
          {
            required: true,
            message: '手机号不能为空'
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码格式错误'
          }
        ],
        password: [{ required: true, message: '密码不能为空' }]
      }
    }
  },
  methods: {
    ...mapMutations('user', ['setTokens']),
    async onSubmit() {
      this.isLoading = true
      try {
        const {
          data: { errmsg, errno, data }
        } = await userLogin(this.username, this.password)
        this.$toast.success(errmsg)
        if (errno === 0) {
          // console.log(data.token)
          // 调用 user模块里面的setTokens方法 存储token
          this.setTokens(data.token)
          // 跳转首页
          const back = this.$route.query.back || '/mine'
          const falg = this.$route.query.falg
          this.$toast.success('登录成功')
          if (falg) {
            return this.$router.back()
          }
          this.$router.push(back)
        }
      } catch (e) {
        console.log(e)
        this.$toast.fail('登录失败')
      }
      this.isLoading = false
    },

    reg() {
      this.$router.push('/register')
    }
  }
}
</script>

<style lang="less" scoped>
h1 {
  text-align: center;
  color: #3196fa;
}

span {
  font-size: 12px;
}
::v-deep {
  .van-nav-bar__content {
    background-color: #3196fa;
  }
  .van-nav-bar__title {
    color: #fff;
  }
  .van-icon.van-icon-arrow-left.van-nav-bar__arrow {
    color: #fff;
  }
}
</style>
